<template>
	<view class="car-container">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="header-content">
				<text class="header-title">购物车</text>
				<!-- <view class="header-right">
					<text class="delete-btn">删除</text>
				</view> -->
			</view>
		</view>
		<view class="top"></view>
		<!-- 购物车商品列表 -->
		<view class="cart-list" v-if="cartList.length > 0">
			<view class="cart-item" v-for="(item, index) in cartList" :key="index">
				<!-- 选择框 -->
				<view class="select-box" @click="toggleSelect(index)" v-if="item.productNum > 0">
					<image :src="item.selected ? '/static/car/car_select.png' : '/static/car/car_no_select.png'"
						class="select-icon"></image>
				</view>

				<!-- 商品信息 -->
				<view class="item-content" v-if="item.productNum > 0">
					<image :src="item.mainImage" class="item-image"></image>
					<view class="item-info">
						<view class="item-header">
							<!-- <image :src="item.tag" mode="" class="item-tag"></image> -->
							<text class="item-title">{{ item.productTitle }}</text>
						</view>
						<view class="item-location">
							<image src="/static/address.png" class="location-icon"></image>
							<text class="location-text">{{ item.areaAddr }}</text>
						</view>
						<view class="item-bottom">
							<view class="price-info">
								<text class="current-price">¥{{ item.productPrice }}</text>
								<text class="unit">{{ item.unit }}</text>
								<text class="original-price">{{ item.originalPrice }}</text>
							</view>
							<!-- 数量控制 -->
							<view class="quantity-control">
								<view class="quantity-btn" @click="decreaseQuantity(index)">
									<!-- <image :src="item.productNum > 1 ? '/static/car/car_sub.png' : '/static/car/car_sub_1.png'" class="control-icon"></image> -->
									<image src="/static/car/car_sub.png" class="control-icon"></image>
								</view>
								<text class="quantity-text">{{ item.productNum }}</text>
								<view class="quantity-btn" @click="increaseQuantity(index)">
									<image src="/static/car/car_add.png" class="control-icon"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="cart-list" v-else>
			<view class="cart-no-list">
				<image class="no-product-car" src="/static/no-car.png"></image>
				<text class="no-product-text">暂无商品,快去加购吧</text>
			</view>
		</view>

		<!-- 猜你喜欢 -->
		<view class="recommend-section">
			<view class="recommend-header">
				<image src="/static/car/car_1.png" class="heart-icon-line"></image>
				<image src="/static/car/car_3.png" class="heart-icon"></image>
				<text class="recommend-title">猜你喜欢</text>
				<image src="/static/car/car_2.png" class="heart-icon-line"></image>
			</view>
			<view class="recommend-list">
				<view class="recommend-item" v-for="(item, index) in recommendList" :key="index"
					@click="goToDetail(item)">
					<image :src="item.mainImage" class="recommend-image"></image>
					<view class="recommend-info">
						<text class="recommend-name">{{ item.title }}</text>
						<view class="recommend-location">
							<image src="/static/address.png" class="location-icon"></image>
							<text class="location-text">{{ item.area }}</text>
						</view>
						<view class="recommend-add">
							<view class="price-info">
								<text class="current-price">{{item.price}}</text>
								<text class="unit">{{item.unit}}</text>
								<text class="original-price">{{item.underlinePrice}}</text>
							</view>
							<image src="/static/home/home_add.png" class="add-icon" @tap.stop="addProduct(item)">
							</image>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部结算栏 -->
		<view class="bottom-bar">
			<view class="bottom-left">
				<view class="select-all" @click="toggleSelectAll">
					<image :src="isAllSelected ? '/static/car/car_select.png' : '/static/car/car_no_select.png'"
						class="select-icon"></image>
					<text class="select-all-text">全选</text>
				</view>
				<view class="vip-price-info">
					<view>
						<text class="selected-info">已选{{ selectedCount }}件，合计：</text>
						<text class="total-price">¥{{ totalPrice }}</text>
					</view>
					<!-- <view>
						<text class="vip-price">会员优惠:18.2</text>
					</view> -->
				</view>
			</view>
			<view class="checkout-btn" @click="buyNow">
				<text class="checkout-text">去结算({{ selectedCount }})</text>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		ORDER_TYPE,
		ORDER_STATUS
	} from '@/utils/status.js'
	export default {
		data() {
			return {
				carOrder: null,
				cartList: [],
				recommendList: []
			}
		},
		onShow() {
			if (uni.getStorageSync('token')) {
				this.requestCartList()
				this.requestGoodsList()
			} else {
				// 未登录时清空购物车角标
				this.clearCartCount();
			}
		},
		onLoad() {
			if (!uni.getStorageSync('token')) {
				this.go('/subPackages/mine/login/login')
				return
			}
			this.requestCartList()
			this.requestGoodsList()
		},
		computed: {
			// 是否全选
			isAllSelected() {
				return this.cartList.length > 0 && this.cartList.every(item => item.selected);
			},
			// 已选商品数量
			selectedCount() {
				return this.cartList.filter(item => item.selected).reduce((total, item) => {
					return total + (item ? item.productNum : 0);
				}, 0);
			},
			// 总价格
			totalPrice() {
				return this.cartList.filter(item => item.selected).reduce((total, item) => {
					if (item) {
						const price = parseFloat(item.productPrice) || 0;
						const num = item.productNum || 0;
						return total + (price * num);
					}
					return total;
				}, 0).toFixed(2);
			}
		},
		methods: {
			//请求购物车商品
			requestCartList() {
				let that = this
				that.https({
					method: "GET",
					url: '/project/order/listCart',
					success: res => {
					console.log("res CartList-------- ", res)
					if (res.code == 200) {
						// 为每个商品添加 selected 字段，默认为 false
						if(res.rows.length > 0){
							that.carOrder = res.rows[0]
							that.cartList = res.rows[0].details.filter(item => item.productNum > 0).map(item => ({
								...item,
								selected: false
							}))
							// 更新购物车角标数量
							const totalCount = that.cartList.reduce((total, item) => {
								return total + (item.productNum || 0);
							}, 0);
							that.setCartCount(totalCount);
						}else{
							that.cartList = []
							that.setCartCount(0);
						}
						
					} else {
						// 购物车为空时清空角标
						that.clearCartCount();
					}
				},
					fail: err => {},
					complete: com => {}
				})
			},
			//添加商品
			addProduct(item) {
				console.log(" add product ===== ", item)
				let that = this
				const orderData = {
					orderType: 1,
					details: [{
						productId: item.id,
						mainImage: item.mainImage,
						productTitle: item.title,
						productPrice: item.price,
						productNum: 1,
						unit: item.unit,
						areaAddr: item.area,
					}],
				}
				that.https({
					method: "POST",
					url: '/project/order/editCart',
					data: orderData,
					success: res => {
					if (res.code == 200) {
						uni.showToast({
							title: '已添加到购物车',
							icon: 'success'
						});
						console.log("res addProduct -----  ", res)
						that.requestCartList()
						// 增加购物车角标数量
						that.addCartCount(1);
					}
				},
					fail: err => {},
					complete: com => {}
				})
			},
			//商品列表
			requestGoodsList() {
				let that = this
				that.https({
					method: "GET",
					url: '/project/product/list',
					data: {
						pageSize: 20,
						pageNum: 1,
					},
					success: res => {
						if (res.code == 200) {
							console.log("res GoodsList -----  ", res)
							that.recommendList = res.rows
						}
					},
					fail: err => {},
					complete: com => {}
				})
			},
			// 切换单个商品选择状态
			toggleSelect(index) {
				this.cartList[index].selected = !this.cartList[index].selected;
				console.log("this.cartList ----- ", this.cartList)
			},
			// 切换全选状态
			toggleSelectAll() {
				const allSelected = this.isAllSelected;
				this.cartList.forEach(item => {
					item.selected = !allSelected;
				});
			},
			// 增加数量
			increaseQuantity(index) {
				// if (this.cartList[index].details && this.cartList[index]) {
				// 	this.cartList[index].productNum++;
				// }
				this.carProductCount(index, 'add')
			},
			// 减少数量
			decreaseQuantity(index) {
				// if (this.cartList[index].details && this.cartList[index] && this.cartList[index].productNum > 1) {
				// 	this.cartList[index].productNum--;
				// }
				// if (this.cartList[index] && this.cartList[index].productNum > 1) {
					this.cartList[index].productNum--;
					this.carProductCount(index, 'sub')
				// }
			},
			goToDetail(item) {
				this.go(`/subPackages/classify/goodsDetail/goodsDetail?id=${item.id}`)
			},
			//购物车商品的数量加减
			carProductCount(index, type) {
				let that = this
				// 深拷贝，防止修改原数据影响页面
				const item = JSON.parse(JSON.stringify(that.cartList[index]));

				console.log("item -------- ", item)
				if (type === 'add') {
					item.productNum = 1
				} else if (type === "sub") {
					item.productNum = -1
				}

				that.carOrder.details = [item]

				that.https({
					method: "POST",
					url: '/project/order/editCart',
					data: that.carOrder,
					success: res => {
						if (res.code == 200) {
							// uni.showToast({
							// 	title: '已添加到购物车',
							// 	icon: 'success',
							// });
							console.log("res addProduct -----  ", res.data)
							console.log("res cartList -----  ", that.cartList)
							that.carOrder = res.data
							
							if (res.data.details.length === 0) {
								that.cartList.splice(index, 1);
							} else {
								const list = res.data.details.filter(item => item.productNum > 0)
								console.log("res addProduct -----  ", list)
								
								if(list.length> 0){
									list.forEach(item => {
										console.log("item 111------ ", item)
										if (item.id === that.cartList[index].id) {
											that.cartList[index].productNum = item.productNum
										}
									})
								}else{
									that.requestCartList()
								}
							}
							// 更新购物车角标数量
							const totalCount = that.cartList.reduce((total, item) => {
								return total + (item.productNum || 0);
							}, 0);
							that.setCartCount(totalCount);
						}
					},
					fail: err => {},
					complete: com => {}
				})
			},
			buyNow(){
				this.reqeustGoodsInventory()
			},
			//请求库存
			reqeustGoodsInventory(){
				const filteredData = this.cartList.filter(item => item.selected === true);
				console.log("filteredData ------ ",filteredData)
				
				let that = this
				const data = filteredData
				that.https({
					method: "POST",
					url: `/project/order/checkInventory`,
					data:data,
					success: res => {
						console.log("res -------- ", res)
						if(res.msg.length > 0){
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}else{
							this.requestAddOrder()
						}
					},
					fail: err => {},
					complete: com => {}
				})
			},
			//新增订单
			requestAddOrder(){
				let that = this
				let  orderData 
				const filteredData = this.cartList.filter(item => item.selected === true);
				console.log("filteredData ------ ",filteredData)
				
				if(filteredData.length>0){
					 const product =  {
						 orderType:'1',
						 realPrice:this.totalPrice,
						 details:filteredData}
					
					uni.setStorageSync('productData', JSON.stringify(product))
					this.go(`/subPackages/cart/orderPay/orderPay`);
				}else{
					uni.showToast({
						title: '请选择商品',
						icon: 'none',
					});
					return
				}
				
				
			// 	if(filteredData.length>0){
			// 		orderData = {
			// 			orderType:ORDER_TYPE.GOODS,
			// 			orderStatus:ORDER_STATUS.PENDING_PAYMENT,
			// 			realPrice:this.totalPrice,
			// 			userId: this.getUserId(), 
			// 			details:filteredData
			// 		};
			// 	}else{
			// 		uni.showToast({
			// 			title: '请选择商品',
			// 			icon: 'none',
			// 		});
			// 		return
			// 	}
			// 	console.log("orderData ------ ",orderData)
			// 	that.https({
			// 		method: "POST",
			// 		url: '/project/order',
			// 		data:orderData,
			// 		success: res => {
			// 			if (res.code == 200) {
			// 				console.log("res AddOrder ------ ",res)
			// 				this.go(`/subPackages/cart/orderPay/orderPay?orderId=${res.data.id}`);
			// 			}
			// 		},
			// 		fail: err => {}, 
			// 		complete: () => {},
			// 	})
			
			},
		}
	}
</script>

<style lang="scss">
	.car-container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 16rpx;
	}

	/* 顶部导航栏 */
	.header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
		background-color: white;
		padding: 88rpx 48rpx 30rpx;
		border-bottom: 1px solid #f0f0f0;

		.header-content {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.header-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}

			.header-right {
				display: flex;
				align-items: center;
			}

			.delete-btn {
				color: #666;
				font-size: 28rpx;
				margin-top: 20rpx;
				margin-right: 30vw;
			}
		}
	}
	.top{
		height: 1rpx;
	}
	/* 购物车列表 */
	.cart-list {
		margin: 180rpx 30rpx 20rpx 30rpx;
		border-radius: 24rpx;
		background-color: white;

		.cart-no-list {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 150rpx 0;

			.no-product-car {
				width: 360rpx;
				height: 360rpx;
			}

			.no-product-text {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #333333;
				line-height: 42rpx;
				text-align: center;
			}
		}

		.cart-item {
			padding: 30rpx;
			display: flex;
			align-items: center;
			position: relative;

			.select-box {
				margin-right: 30rpx;
				padding-top: 10rpx;

				.select-icon {
					width: 40rpx;
					height: 40rpx;
				}
			}

			.item-content {
				flex: 1;
				display: flex;

				.item-image {
					width: 160rpx;
					height: 160rpx;
					border-radius: 8rpx;
					margin-right: 14rpx;
				}

				.item-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: center;

					.item-header {
						display: flex;
						align-items: center;

						.item-title {
							font-size: 16px;
							font-weight: bold;
							color: #333;
						}

						.item-tag {
							width: 64rpx;
							height: 28rpx;
						}
					}

					.item-location {
						display: flex;
						align-items: center;
						margin: 20rpx 0;

						.location-icon {
							width: 24rpx;
							height: 24rpx;
							margin-right: 10rpx;
						}

						.location-text {
							font-size: 24rpx;
							color: #999;
						}
					}

					.item-bottom {
						width: 100%;
						display: flex;
						justify-content: space-between;
						align-items: center;

						.price-info {
							display: flex;
							align-items: baseline;

							.current-price {
								font-family: PingFang SC, PingFang SC;
								font-weight: 600;
								font-size: 36rpx;
								color: #FF4C10;
								text-align: left;
								margin-right: 8rpx;
							}

							.unit {
								font-size: 24rpx;
								color: #999;
								margin-right: 8rpx;
							}

							.original-price {
								font-size: 24rpx;
								color: #999;
								text-decoration: line-through;
							}
						}

						/* 数量控制 */
						.quantity-control {
							display: flex;
							align-items: center;

							.quantity-btn {
								width: 56rpx;
								height: 56rpx;
								display: flex;
								align-items: center;
								justify-content: center;
							}

							.control-icon {
								width: 40rpx;
								height: 40rpx;
							}

							.quantity-text {
								font-size: 32rpx;
								color: #333;
								min-width: 40rpx;
								text-align: center;
							}
						}
					}
				}
			}
		}
	}

	/* 猜你喜欢 */
	.recommend-section {
		margin: 48rpx 30rpx 20rpx;
		margin-bottom: 160rpx;

		.recommend-header {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 30rpx;

			.heart-icon {
				width: 40rpx;
				height: 40rpx;
				margin-right: 16rpx;
			}

			.heart-icon-line {
				width: 60rpx;
				height: 2rpx;
				margin-right: 16rpx;
			}

			.recommend-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

		}

		.recommend-list {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.recommend-item {
				width: 48%;
				background-color: white;
				border-radius: 24rpx;
				position: relative;
				margin-bottom: 20rpx;

				.recommend-image {
					width: 100%;
					height: 334rpx;
					border-radius: 16rpx 16rpx 0 0;
				}

				.recommend-info {
					position: relative;
					margin: 16rpx;

					.recommend-name {
						font-family: PingFang SC, PingFang SC;
						font-weight: 500;
						font-size: 28rpx;
						color: #333333;
						text-align: left;
					}

					.recommend-location {
						display: flex;
						align-items: center;
						margin-bottom: 10rpx;

						.location-icon {
							width: 24rpx;
							height: 24rpx;
						}

						.location-text {
							font-family: PingFang SC, PingFang SC;
							font-weight: 500;
							font-size: 20rpx;
							color: #333333;
							text-align: left;
						}
					}

					.recommend-add {
						width: 100%;
						display: flex;
						align-items: center;
						justify-content: space-between;

						.price-info {
							display: flex;
							align-items: baseline;

							.current-price {
								font-family: PingFang SC, PingFang SC;
								font-weight: 600;
								font-size: 24rpx;
								color: #FF4C10;
								text-align: left;
								margin-right: 8rpx;
							}

							.unit {
								font-family: PingFang SC, PingFang SC;
								font-weight: 500;
								font-size: 20rpx;
								color: #333333;
								text-align: left;
								margin-right: 8rpx;
							}

							.original-price {
								font-family: PingFang SC, PingFang SC;
								font-weight: 400;
								font-size: 20rpx;
								color: #767676;
								text-align: left;
								text-decoration: line-through;
							}
						}

						.add-icon {
							width: 48rpx;
							height: 48rpx;
						}
					}
				}
			}
		}
	}

	/* 底部结算栏 */
	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: white;
		padding: 15px 20px;
		border-top: 1px solid #f0f0f0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
	}

	.bottom-left {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.select-all {
		display: flex;
		align-items: center;
		margin-right: 15px;
	}

	.select-all-text {
		font-size: 14px;
		color: #333;
		margin-left: 5px;
	}

	.vip-price-info {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.vip-price {
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #666666;
		text-align: left;
	}

	.selected-info {
		font-size: 24rpx;
		color: #666;
	}

	.total-price {
		font-size: 32rpx;
		font-weight: bold;
		color: #FF6B35;
	}

	.checkout-btn {
		background: #009966;
		border-radius: 20px;
		padding: 10px 20px;
	}

	.checkout-text {
		color: white;
		font-size: 14px;
		font-weight: bold;
	}

	.select-icon {
		width: 40rpx;
		height: 40rpx;
	}
</style>